import requests
from flask import session

from util.constant import Constant
from util.request_helper import get_image_path


def get_restaurant_info(restaurant_id, cookie):
    longitude = session.get("longitude")
    latitude = session.get("latitude")
    headers = {
        "accept": "application/json, text/plain, */*",
        "referer": "https://h5.ele.me/msite/food/",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        'x-shard': 'loc=' + str(longitude) + ',' + str(latitude),
        'x-ua': 'RenderWay/H5 AppName/wap',
        'x-uab': '124#4EuJ2JztxG0xAPcjR0c7HeKVVpRFx4SskGO1Me+5ZXguXA0v3UtKPvNmSMx+Zk+hswFEEFeDtxEXu2TOmxnkyZRY5nrxzND3ysE3Vn/sUUswJlNDK33AqOYC4qPmUOTH4GOY4X6BnuhZkZrSWwkwLigMKS02lTj/4QuGkDRRZRw/K01G8kUxInYLlTYIm4WZIqXLgTzd1Z2ebUL2gKvm/UwT5wiJm4afI8LpgTG41nIelUX2g7vtIZ/Llm/Jm4WZIqXLg5Sd1Z2ZlMLng7OBInYLlwYnmfWxJMbBgmUd1qyelULnm6tu0U9LUTY2USAeIqXpgxMTxilGvwi5uEqNRldbhEM2fFlnzJ1/a/vtDwL4Q0LQrMxN76oGQj3TplEcoyFbjMd4AJFl4Udi+O61SJ9Dv2tYxwu5+Dl3p7MlBSBmHG1tpBy82VTcBoLVLz1Rm6Xi7tnrwu7fQrhTxQYUzkWuxz1g4Bc5eaqQmP5QI2WHO12JVJ5Ye0QGmAuaRzipiKcOu3GqUhvXZ+1I1ua6HWwcBcUToyAqC2vYD+QNd0fPRSROWVAwJ1mRlGX7uGgswmaQJOvBOtB1Xx7P/QbLg/tRL5W4ubLMoJ0B4QaRhzA0/RCGtqAAHWnH1gjYoQQz/NddhdTleWJfr3oevsA7OuBeICYaBf9kIrlV9EdM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Fs/5KhxSZPK8aVGnY+nI93MzXgfzUvGGupPNEBGZd+Z5qaee56vzi97Pdiw1QTrKMgRcj0RXCET8GovOA3N48fdH0YQ7v/FWDntg7oXp++Qs2JyFU6NNewmg+YiQ1ADY4V4RiZtnayFnlh0Zrz3od3M0mnI/44dVw4A8Hl//QL5btwnEPBYQRsISCFIetxBOip90X9TN+c+dAKnMPJtFyPt+MJOu1i0aK+UyV+n76RELdxLN0YkY40Rn4HTFgiNjXcXvRrh7r0OnMtzSsNzFbAOGJeQi4aBysbxRNp7QBILMme8HZ1ih8ERV'
    }
    sess = requests.Session()
    restaurant_detail_request = sess.get(Constant.get_restaurant_detail_url(restaurant_id), headers=headers,
                                         cookies=cookie)
    response = restaurant_detail_request.json()
    # 商家基本信息字段
    restaurant_info = response['rst']
    # 商家图片地址
    restaurant_image = get_image_path(restaurant_info['image_path'])
    # 商家名称
    restaurant_name = restaurant_info['name']
    # 评价
    rating = restaurant_info['rating']
    # 月售
    recent_order_num = restaurant_info['recent_order_num']
    # 配送时间
    order_lead_time = restaurant_info['order_lead_time']
    result = {
        'restaurant_name': restaurant_name,
        'restaurant_image': restaurant_image,
        'rating': rating,
        'recent_order_num': recent_order_num,
        'order_lead_time': order_lead_time
    }
    # 菜单列表
    restaurant_food = response['menu']
    food_list = []
    for menu in restaurant_food:
        foods = menu['foods']
        for food in foods:
            # 食物名称
            food_name = food['name']
            # 食物月售（销量）
            food_sales = food['month_sales']
            # 食物价格
            food_price = food['price']
            # 满意度
            satisfaction = food['satisfy_rate']
            food_list.append({
                "food_name": food_name,
                "food_sales": food_sales,
                "food_price": food_price,
                "satisfaction": satisfaction
            })
    # 去重
    food_list = [dict(t) for t in set([tuple(d.items()) for d in food_list])]
    # 按销量排序
    food_list.sort(key=lambda x: x['food_sales'], reverse=True)
    result['food'] = food_list
    return result


def get_restaurant_comments(restaurant_id, cookie):
    longitude = session.get("longitude")
    latitude = session.get("latitude")
    headers = {
        "accept": "application/json, text/plain, */*",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        'x-shard': 'loc=' + str(longitude) + ',' + str(latitude),
        'x-ua': 'RenderWay/H5 AppName/wap',
        'x-uab': '124#4EuJ2JztxG0xAPcjR0c7HeKVVpRFx4SskGO1Me+5ZXguXA0v3UtKPvNmSMx+Zk+hswFEEFeDtxEXu2TOmxnkyZRY5nrxzND3ysE3Vn/sUUswJlNDK33AqOYC4qPmUOTH4GOY4X6BnuhZkZrSWwkwLigMKS02lTj/4QuGkDRRZRw/K01G8kUxInYLlTYIm4WZIqXLgTzd1Z2ebUL2gKvm/UwT5wiJm4afI8LpgTG41nIelUX2g7vtIZ/Llm/Jm4WZIqXLg5Sd1Z2ZlMLng7OBInYLlwYnmfWxJMbBgmUd1qyelULnm6tu0U9LUTY2USAeIqXpgxMTxilGvwi5uEqNRldbhEM2fFlnzJ1/a/vtDwL4Q0LQrMxN76oGQj3TplEcoyFbjMd4AJFl4Udi+O61SJ9Dv2tYxwu5+Dl3p7MlBSBmHG1tpBy82VTcBoLVLz1Rm6Xi7tnrwu7fQrhTxQYUzkWuxz1g4Bc5eaqQmP5QI2WHO12JVJ5Ye0QGmAuaRzipiKcOu3GqUhvXZ+1I1ua6HWwcBcUToyAqC2vYD+QNd0fPRSROWVAwJ1mRlGX7uGgswmaQJOvBOtB1Xx7P/QbLg/tRL5W4ubLMoJ0B4QaRhzA0/RCGtqAAHWnH1gjYoQQz/NddhdTleWJfr3oevsA7OuBeICYaBf9kIrlV9EdMAnt8wvZFkucmubVIUqTCA0bkoTBYIuRPyphtmJDkRhUyq2EriFmtLb6hOi8SWa+e47OFTBH7h6vIWSQK7zJImRUi7Z+2wIYqfp0CvFAUcq0ITZU/usjHMHTpG5o05tf5OzbVvzCNcCXIzWa8s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rz3od3M0mnI/44dVw4A8Hl//QL5btwnEPBYQRsISCFIetxBOip90X9TN+c+dAKnMPJtFyPt+MJOu1i0aK+UyV+n76RELdxLN0YkY40Rn4HTFgiNjXcXvRrh7r0OnMtzSsNzFbAOGJeQi4aBysbxRNp7QBILMme8HZ1ih8ERV'
    }
    result = {}
    sess = requests.Session()
    good_params = {
        "has_content": "true",
        "tag_name": "好评",
        "offset": 0,
        "limit": 4
    }
    bad_params = {
        "has_content": "true",
        "tag_name": "差评",
        "offset": 0,
        "limit": 4
    }
    # 爬取评价数量
    restaurant_batch_comment_request = sess.get(Constant.get_batch_comment_url(restaurant_id), headers=headers,
                                                cookies=cookie)
    batch_comment_response = restaurant_batch_comment_request.json()
    tag_list = []
    tags = batch_comment_response['tags']
    for tag in tags:
        # 过滤最新
        if tag['name'] != '最新':
            tag_list.append({
                "name": tag['name'],
                "count": tag['count']
            })
    result['tags'] = tag_list
    good_comment_list = []
    # 爬取好评
    restaurant_good_comment_request = sess.get(Constant.get_rating_url(restaurant_id), params=good_params,
                                               headers=headers,
                                               cookies=cookie)
    restaurant_good_comment_response = restaurant_good_comment_request.json()
    for good_comment in restaurant_good_comment_response:
        good_comment_list.append({
            "rating_text": good_comment['rating_text']
        })
    bad_comment_list = []
    # 爬取差评
    restaurant_bad_comment_request = sess.get(Constant.get_rating_url(restaurant_id), params=bad_params,
                                              headers=headers,
                                              cookies=cookie)
    restaurant_bad_comment_response = restaurant_bad_comment_request.json()
    for bad_comment in restaurant_bad_comment_response:
        bad_comment_list.append({
            "rating_text": bad_comment['rating_text']
        })
    result['good_comments'] = good_comment_list
    result['bad_comments'] = bad_comment_list
    return result
